<?php
namespace CommonTrait;

trait Controller
{

    public $hasJump = false;

    public function cors()
    {
        $this->response->header('Access-Control-Allow-Origin', '*', true);
    }

    public function json()
    {
        $this->response->header('Content-Type', 'application/json', true);
    }

    public function html()
    {
        $this->response->header('Content-Type', 'text/html', true);
    }

    public function downloadZip($fileName = 'test.zip')
    {
        $this->response->header('Content-Type', 'application/octet-stream', true);
        $this->response->header('Content-Disposition', "attachment;filename={$fileName}", true);
    }

    public function send($data = '')
    {
        $this->response->end($data);
    }

    public function sendSuccess($data = [])
    {
        $json = makeSuccess($data);
        $this->response->end($json);
        return $json;
    }

    public function sendFail($key = 'FAIL', $diy = '', $line = 0)
    {
        $json = makeFail($key, $diy, $line);
        $this->response->end($json);
    }

    public function isPost()
    {
        return $this->request->server['request_method'] == 'POST';
    }

    public function getQueryData()
    {
        return $this->request->get;
    }

    public function getPostData()
    {
        return $this->request->post;
    }

    public function getHeaderData()
    {
        return $this->request->header;
    }

    public function getServerData()
    {
        return $this->request->server;
    }

    public function getRequestData()
    {
        $data = [];
        if(!empty($this->request->get)){
            $data = array_merge($data, $this->request->get);
        }
        if(!empty($this->request->post)){
            $data = array_merge($data, $this->request->post);
        }
        return $data;
    }

    public function getDataPlus($name = '')
    {
        $data = $this->getRequestData();
        if(isset($data[$name])){
            return $data[$name];
        }
        $data = $this->request->cookie;
        if(isset($data[$name])){
            return $data[$name];
        }
        return '';
    }

    public function getToken()
    {
        return $this->getDataPlus('token');
    }

    public function getGroup()
    {
        return $this->getDataPlus('group');
    }

    public function jump($url)
    {
        $this->hasJump = true;
        $this->response->redirect($url);
    }

}